#标准库，用于创建图形用户界面（GUI），支持窗口、按钮、文本框等控件的创建和管理。
import tkinter as tk
from tkinter import PhotoImage
from tkinter import messagebox
#第三方库，用于图像处理，支持图像打开、编辑、保存、格式转换等操作。Pillow 是 PIL 的现代分支，功能更强大且兼容性更好。
from PIL import Image, ImageTk, ImageDraw, ImageFont
from .Shared import *

player = shareddata.get_player()

#工坊界面
class PageForge(tk.Frame):

    def __init__(self, parent):
        super().__init__(parent)
        self.configure(bg = "white", width = 1200, height = 720)
        # 禁止自动调整大小
        self.pack_propagate(False) 
        self.bind("<Expose>", lambda event: self.on_raise(event, parent))
        global player
        player = shareddata.get_player()

        #加载界面变量
        #界面按钮
        self.pagebuttonlist = ["", "", "", "", ""]
        self.pagebuttontextlist = ["PageHome", "PageRole", "PageForge", "PageFight", "PageSet"]
        self.pagebuttonid = []
        self.nowpage = 2
        self.equipmentlist = [["weapon", "enchant"], ["clothes", "core"], ["shoes", "medal"]]
        #装备栏按钮
        self.quality = tk.StringVar()
        self.quality.set("perfect")  
        self.qualitys = [("perfect", "0", "red"),("legendary", "1", "yellow"),("unique", "2", "purple"),("rare", "3", "blue"),("common", "4", "green")]
        self.qualitybuttonlist = []
        self.equipbuttonlist = []
        self.equipbuttonid = []
        self.equipmentlist = shareddata.equipmentlist
        self.nowequip = 0
        #加载图像资源
        self.picture ={
            "PageForge": shareddata.get_picture("PageForge"),
            "Resources": shareddata.get_picture("Resources"),
            "EquipmentList": shareddata.get_picture("EquipmentList")
        }
        #加载动画缓冲画布
        self.buffer_image = Image.new("RGBA", (1200, 720), (255, 255, 255, 0))
        self.canvas = tk.Canvas(self, width = 1200, height = 720, highlightthickness = 0, bd = 0)
        self.canvas.place(x = 0, y = 0)

        #界面按钮
        for i in range(5):
            self.pagebuttonlist[i] = tk.Canvas(self, bg = "#FFFFFF" if (i != self.nowpage) else "#87CEFA", width = 80, height = 80, highlightthickness = 0, bd = 0)
            self.pagebuttonlist[i].place(x = 600 + 120 * i, y = 10)
            self.pagebuttonid.append(self.pagebuttonlist[i].create_image(0, 0, anchor = tk.NW, image = self.picture["Resources"]["ButtonList"][i][1]))
            self.pagebuttonlist[i].bind("<Enter>", lambda event, i = i: self.mouse_enter(event, self.nowpage, i, self.pagebuttonlist[i]))
            self.pagebuttonlist[i].bind("<Leave>", lambda event, i = i: self.mouse_leave(event, self.nowpage, i, self.pagebuttonlist[i]))
            self.pagebuttonlist[i].bind("<Button-1>", lambda event, i = i: parent.show_frame(self.pagebuttontextlist[i]))

        smallfont = ImageFont.truetype(shareddata.get_font_path(), 15)
        self.quality.set("0") 
        for text, val, color in self.qualitys:
            #                                                                                                 又犯傻了，刚开始又忘写回调函数导致加载期间就调用运行而触发事件却无法调用运行
            self.qualitybuttonlist.append(tk.Radiobutton(self, text = text, font=(shareddata.get_font_path(), 15), fg=color, variable = self.quality, value = val, command = lambda: self.on_change()))
            self.qualitybuttonlist[-1].place(x = 250 + 150 * int(val), y = 150)

        #装备栏按钮 
        for i in range(6):
            self.equipbuttonlist.append(tk.Canvas(self, bg = "#FFFFFF" if (i != self.nowequip) else "#87CEFA", width = 300, height = 120, highlightthickness = 0, bd = 0))
            self.equipbuttonlist[i].place(x = 75 + 375 *  (i % 3), y = 250 + 150 * (i // 3))
            word = ""
            for key, value in self.equipmentlist[int(self.quality.get())][i].items():
                word += key + ": " + str(value) + "\n" 
            self.equipbuttonid.append((self.equipbuttonlist[i].create_image(0, 0, anchor = tk.NW, image = self.picture["EquipmentList"]["Frame"][int(self.equipmentlist[0][i]["No."].split(".")[0])][1]), 
                                       self.equipbuttonlist[i].create_image(10, 10, anchor = tk.NW, image = self.picture["EquipmentList"]["0"][int(self.equipmentlist[0][i]["No."].split(".")[1])][1]), 
                                       self.equipbuttonlist[i].create_text(100, 0, anchor=tk.NW, text = word, fill = "black", font = (shareddata.get_font_path(), 15))
                                       ))
            self.equipbuttonlist[i].bind("<Enter>", lambda event, i = i: self.mouse_enter(event, self.nowequip, i, self.equipbuttonlist[i]))
            self.equipbuttonlist[i].bind("<Leave>", lambda event, i = i: self.mouse_leave(event, self.nowequip, i, self.equipbuttonlist[i]))
            self.equipbuttonlist[i].bind("<Button-1>", lambda event, i = i: self.show_equipment(i))

        #锻造按钮
        self.creatbutton = tk.Canvas(self, bg = "#FFFFFF", width = 70, height = 30, highlightthickness = 0, bd = 0)
        self.creatbutton.place(x = 565, y = 650)
        self.creatbutton.create_image(0, 0, anchor = tk.NW, image = self.picture["Resources"]["EqRmButton"][1])
        self.creatbutton.bind("<Enter>", lambda event: self.mouse_enter(event, 0, 999, self.creatbutton))
        self.creatbutton.bind("<Leave>", lambda event: self.mouse_leave(event, 0, 999, self.creatbutton))
        self.creatbutton.bind("<Button-1>", lambda event: self.creat())

        #动画缓冲
        self.update_buffer(parent)

    #界面抬升触发事件
    def on_raise(self, event, parent):
        global player
        player = shareddata.get_player()
        self.update_buffer(parent) 

    #动画缓冲之画面上传
    def update_buffer(self, parent):
        self.buffer_image.paste((255, 255, 255, 0), [0, 0, 1200, 720])
        self.draw_to_buffer(self.buffer_image, parent)
        self.photo_buffer = ImageTk.PhotoImage(self.buffer_image)
        self.canvas.create_image(0, 0, image = self.photo_buffer, anchor = tk.NW)

    #动画缓冲之绘制缓冲画面
    def draw_to_buffer(self, buffer_image, parent):
        global player
        player = shareddata.get_player()
        draw = ImageDraw.Draw(buffer_image)
        headfont = shareddata.get_font(30)
        smallfont = ImageFont.truetype(shareddata.get_font_path(), 15)
        draw.rectangle([0, 0, 1200, 720], fill=(255, 255, 255, 0)) 
        #背景
        #buffer_image.paste(self.picture["PageForge"]["BackGround"][0], (0, 0), self.picture["PageForge"]["BackGround"][0])
        #左上头像框   
        buffer_image.paste(self.picture["Resources"]["HeadFrame"][0], (0, 0), self.picture["Resources"]["HeadFrame"][0]) 
        buffer_image.paste(self.picture["Resources"]["KianaHead"][0], (20, 10), self.picture["Resources"]["KianaHead"][0]) 
        buffer_image.paste(self.picture["Resources"]["Crystal"][0], (120, 50), self.picture["Resources"]["Crystal"][0]) 
        buffer_image.paste(self.picture["Resources"]["Coin"][0], (270, 50), self.picture["Resources"]["Coin"][0]) 
        draw.text((120, 15), player["neckname"], font = headfont) 
        draw.text((270, 15), "LV." + str(player["level"]), font = headfont) 
        draw.text((150, 50), ":" + str(player["crystal"]), font = headfont) 
        draw.text((300, 50), ":" + str(player["coin"]), font = headfont) 
        #中间装备信息展示
        for i in range(6):
            k = 0
            text = ""
            for key, value in self.equipmentlist[int(self.quality.get())][i].items():
                text += key + ": " + str(value) + '\n'     
                k+=1   
        #资源消耗
        buffer_image.paste(self.picture["Resources"]["Crystal"][0], (380, 550), self.picture["Resources"]["Crystal"][0]) 
        buffer_image.paste(self.picture["Resources"]["Coin"][0], (790, 550), self.picture["Resources"]["Coin"][0]) 
        draw.text((395 - 9 * len(str(int(self.equipmentlist[int(self.quality.get())][self.nowequip]["worth"]/10))), 600), str(int(self.equipmentlist[int(self.quality.get())][self.nowequip]["worth"]/10)), fill = self.qualitys[int(self.quality.get())][2], font = headfont) 
        draw.text((805 - 9 * len(str(self.equipmentlist[int(self.quality.get())][self.nowequip]["worth"])), 600), str(self.equipmentlist[int(self.quality.get())][self.nowequip]["worth"]), fill = self.qualitys[int(self.quality.get())][2], font = headfont) 
        
        
        
    def mouse_enter(self, event, cls, now, canvas):
        canvas.config(bg = "#FFD700" if (now != cls) else "#87CEFA")

    def mouse_leave(self, event, cls, now, canvas):
        canvas.config(bg = "#FFFFFF"  if (now != cls) else "#87CEFA")

    def show_equipment(self, now):
        self.equipbuttonlist[self.nowequip].config(bg = "#FFFFFF")
        self.nowequip = now
        self.equipbuttonlist[self.nowequip].config(bg = "#87CEFA")
        self.update_buffer(self.master)

    def on_change(self):
        for i in range(6):
            self.equipbuttonlist[i].itemconfig(self.equipbuttonid[i][0], image = self.picture["EquipmentList"]["Frame"][int(self.quality.get())][1])
            self.equipbuttonlist[i].itemconfig(self.equipbuttonid[i][1], image = self.picture["EquipmentList"][self.quality.get()][int(self.equipmentlist[int(self.quality.get())][i]["No."].split(".")[1])][1])
            word = ""
            for key, value in self.equipmentlist[int(self.quality.get())][i].items():
                word += key + ": " + str(value) + "\n" 
            self.equipbuttonlist[i].itemconfig(self.equipbuttonid[i][2], text = word, fill = "black", font = (shareddata.get_font_path(), 15))
        self.update_buffer(self.master)
    
    def creat(self):
        global player
        player = shareddata.get_player()
        if(player["crystal"] >= int(self.equipmentlist[eval(self.quality.get())][self.nowequip]["worth"]/10) and player["coin"] >= int(self.equipmentlist[eval(self.quality.get())][self.nowequip]["worth"])):
            player["crystal"] -= int(self.equipmentlist[eval(self.quality.get())][self.nowequip]["worth"]/10)
            player["coin"] -= int(self.equipmentlist[eval(self.quality.get())][self.nowequip]["worth"])
            player["bag"].append(self.equipmentlist[eval(self.quality.get())][self.nowequip])
            shareddata.set_player(player)
            self.update_buffer(self.master)
        else:
            messagebox.showinfo("报错哩！！！", "money不够喵, 快去战斗赚钱喵")